import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class CombinationSum0102_39 {

    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        int sum = 0;
        backtracking(candidates,target,sum,0);
        return result;
    }

    private void backtracking(int[] candidates, int target, int sum, int startIndex) {
        if(sum == target){
            result.add(new ArrayList<>(path));
            return;
        }

        if(sum > target) return;

        // 如果 sum + candidates[i] > target 就终止遍历 剪枝操作 前提是已排序
        for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) {
            sum += candidates[i];
            path.add(candidates[i]);
            backtracking(candidates, target, sum,i); //// 注意⚠️关键点:不用i+1了，表示可以重复读取当前的数！！！
            sum -= candidates[i];
            path.removeLast();
        }
    }
}
